package com.project.system.service.impl;

import com.project.common.core.domain.BaseServer;
import com.project.common.core.domain.entity.SysUser;
import com.project.common.core.domain.entity.SysUserWx;
import com.project.common.utils.ProjectUtils;
import com.project.system.domain.SysLogininfor;
import com.project.system.mapper.SysLogininforMapper;
import com.project.system.mapper.SysUserMapper;
import com.project.system.mapper.SysUserWxMapper;
import com.project.system.service.ISysLogininforService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author admin
 */
@Service
public class SysLogininforServiceImpl extends BaseServer implements ISysLogininforService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserWxMapper sysUserWxMapper;

    @Resource
    private SysLogininforMapper logininforMapper;

    private boolean isAdmin;

    public boolean isAdmin() {
        return isAdmin;
    }

    public void setAdmin(boolean admin) {
        isAdmin = admin;
    }

    /**
     * 新增系统登录日志
     *
     * @param logininfor 访问日志对象
     */
    @Override
    @Transactional
    public void insertLogininfor(SysLogininfor logininfor) {
        super.insert(logininfor);
        logininforMapper.insertLogininfor(logininfor);
        SysUser sysUser = sysUserMapper.selectUserByUserName(logininfor.getUserName());
        if (sysUser != null) {
            super.update(sysUser);
            sysUser.setLoginIp(logininfor.getIpaddr());
            sysUser.setLoginDate(new Date());
            sysUserMapper.updateUser(sysUser);
            return;
        }
        SysUserWx sysUserWx = sysUserWxMapper.selectSysUserWxByOpenId(logininfor.getUserName());
        if (sysUserWx != null) {
            super.update(sysUserWx);
            sysUserWx.setLoginIp(logininfor.getIpaddr());
            sysUserWx.setLoginDate(new Date());
            sysUserWxMapper.updateSysUserWx(sysUserWx);
            return;
        }
    }

    /**
     * 查询系统登录日志集合
     *
     * @param logininfor 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public List<SysLogininfor> selectLogininforList(SysLogininfor logininfor) {
        return logininforMapper.selectLogininforList(logininfor);
    }

    /**
     * 批量删除系统登录日志
     *
     * @param infoIds 需要删除的登录日志ID
     * @return
     */
    @Override
    public int deleteLogininforByIds(Long[] infoIds) {
        return logininforMapper.deleteLogininforByIds(infoIds);
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLogininfor() {
        logininforMapper.cleanLogininfor();
    }
}
